//
//  GAOStatusesViewModel.swift
//  Weibo28
//
//  Created by 高辰 on 16/5/14.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit



//GAOStatusesCell 对应的 viewModel
class GAOStatusesViewModel: NSObject {
    var statuses: GAOStatuses?
    //转发微博内容
    var repostContent: String?
    //转发数
    var retweetCount: String?
    
    //评论数
    var commentCont: String?
    //点赞数
    var attitudesCount: String?
    //微博来源
    var sourceContent: String?
    
    //发布时间,根据当前时间和发微博时间进行计算,获取秒数或者进行时间格式化
    var timeContent: String? {
        if let createTime = statuses?.created_at {
            return NSDate.sinaDate(createTime).sinaDateString
        }
        return "来自未来"
    }
    
    //设置会员等级图片
    var mbrankImage: UIImage?
    //设置认证的等级图片
    var verifiedTypeImage: UIImage?
    
    //  原创微博富文本
    var origianlAttributedString: NSAttributedString?
    //  转发微博富文本
    var retweetAttributedString: NSAttributedString?

    
    init(statuses: GAOStatuses) {
        super.init()
        self.statuses = statuses
        makeRepostContent(statuses)
        
        retweetCount = makeCountContent(statuses.reposts_count, defaultTitle: "转发")
        commentCont = makeCountContent(statuses.comments_count, defaultTitle: "评论")
        attitudesCount = makeCountContent(statuses.attitudes_count, defaultTitle: "点赞")
        
        makeSourceStr(statuses)
        
        makeMbrankImageView(statuses.user?.mbrank ?? 0)
        
        makeVerifiedTypeImageView(statuses.user?.verified_type ?? 0)
        
        //  处理微博内容的表情字符串
        //  设置原创微博富文本
        origianlAttributedString = makeEmoticonContentWithStatus(statuses.text!)
    }
    
    //拼接转发微博内容
    private func makeRepostContent(statuses: GAOStatuses) {
        guard let repostText = statuses.retweeted_status?.text else {
            return
        }
        
        guard let name = statuses.retweeted_status?.user?.screen_name else {
            return
        }
        repostContent = "@\(name): \(repostText)"
        
        //  设置转发微博的富文本
        retweetAttributedString = makeEmoticonContentWithStatus(repostContent!)
        
    }
    
    //自定义ToolbarView中button的转发,评论,赞的数据
    private func makeCountContent(count: Int, defaultTitle: String)->String {
        if count > 0 {
            if count >= 10000{
                //处理显示格式
                let result = CGFloat(count) / 10000.0
                let resultStr = "\(result)万"
                
                if resultStr.containsString(".0") {
                    return resultStr.stringByReplacingOccurrencesOfString(".0", withString: "")
                }
                return resultStr
                
            }else {
                return "\(count)"
            }
        }else {
        
            return defaultTitle
        }
    }
    
    //截取微博来源字符串
    private func makeSourceStr(statuses :GAOStatuses) {
        //判断来源数据是否存在
        guard let source = statuses.source else {
            return
        }
        // \ 是转译符
        if source.containsString("\">") {
            guard let startIndex = source.rangeOfString("\">")?.endIndex else {
                return
            }
            guard let endIndex = source.rangeOfString("</")?.startIndex else {
                return
            }
            sourceContent = source.substringWithRange(startIndex..<endIndex)
        }
        
        
    }
    //出路会员等级图片
    private func makeMbrankImageView(mbrank: Int) {
        if mbrank > 0 && mbrank < 7 {
            mbrankImage = UIImage(named: "common_icon_membership_level\(mbrank)")
        }
    }
    //处理认证等级图片
    private func makeVerifiedTypeImageView(verified_type: Int) {
        switch verified_type {
        case 0:
            verifiedTypeImage = UIImage(named: "avatar_vip")
        case 2, 3, 5:
            verifiedTypeImage = UIImage(named: "avatar_enterprise_vip")
        case 220:
            verifiedTypeImage = UIImage(named: "avatar_grassroot")
        default:
            verifiedTypeImage = nil
        }
    }
    
    //  通过微博内容处理里面的表情字符串转表情富文本
    private func makeEmoticonContentWithStatus(status: String) -> NSAttributedString {
        //  将微博内容转成富文本,便于我们后面使用,直接设置给我们原创微博与转发微博的富文本
        let result = NSMutableAttributedString(string: status)
        
        //  根据微博内容匹配表情字符串 '正则表达式'
        //   1. "正则表达式"
        
        //   usingBlock :  1. 匹配格式,2 匹配到内容的指针,3匹配到范围的值,4. 是否停止的指针
        
        var matchResultArray = [GAOMatchResult]()
        
        (status as NSString).enumerateStringsMatchedByRegex("\\[[a-zA-Z0-9\\u4e00-\\u9fa5]+\\]") { (captureCount, captureString, captureRange, _) -> Void in
            
            //  获取指针对应的内容
            
            //  把NSString转成我们需要String
            if let emotionStr = captureString.memory as? String {
                
                let matchResult = GAOMatchResult(string: emotionStr, range: captureRange.memory)
                
                matchResultArray.append(matchResult)
                
            }

    }
        //  倒序遍历
        for value in matchResultArray.reverse() {
            
            if let emoticon = GAOEmoticonTools.shareTools.emoticonWithEmoticonStr(value.string) {
                //  创建表情富文本
                let emoticonAttr = NSAttributedString.attributedWithEmotion(emoticon, font: UIFont.systemFontOfSize(14.0))
//                print(status)
                //  替换表情富文本
                result.replaceCharactersInRange(value.range, withAttributedString: emoticonAttr)
                
            }
            
            
        }
        return result
    }

    
}
